package com.baosight.risk.service.riaa.impl;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baosight.risk.api.fltd.FlaaNodeAuthoService;
import com.baosight.risk.api.fltd.FltdProcessService;
import com.baosight.risk.api.riaa.RiaaQuesInquiryService;
import com.baosight.risk.api.riaa.RiquInquiryCompService;
import com.baosight.risk.api.xtzy.IXtzyCompanyService;
import com.baosight.risk.api.xtzy.IXtzyUserService;
import com.baosight.risk.base.mapper.BaseMapper;
import com.baosight.risk.base.service.BaseServiceImpl;
import com.baosight.risk.common.aspects.factory.AsyncFactory;
import com.baosight.risk.common.bean.BeanUtils;
import com.baosight.risk.common.manager.AsyncManager;
import com.baosight.risk.common.utils.IDGenerator;
import com.baosight.risk.common.utils.StringUtils;
import com.baosight.risk.mapper.riaa.RiaaQuesCompMapper;
import com.baosight.risk.mapper.riaa.RiaaQuesInquiryMapper;
import com.baosight.risk.mapper.riaa.RiaaQuesTypeMapper;
import com.baosight.risk.mapper.riaa.RiaaQuesUserMapper;
import com.baosight.risk.mapper.riaa.RiquInquiryCompMapper;
import com.baosight.risk.mapper.riaa.RiquInquiryDetailMapper;
import com.baosight.risk.mapper.system.SysRoleMapper;
import com.baosight.risk.mapper.system.XsUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompRoleMapper;
import com.baosight.risk.mapper.xtzy.XtzyCompUserMapper;
import com.baosight.risk.mapper.xtzy.XtzyRoleUserMapper;
import com.baosight.risk.service.fltd.vo.FlaaNodeAuthoVO;
import com.baosight.risk.service.fltd.vo.FltdTaskVO;
import com.baosight.risk.service.quartz.entity.SyncEmpleeEntitiy;
import com.baosight.risk.service.riaa.entity.RiaaQuesComp;
import com.baosight.risk.service.riaa.entity.RiaaQuesInquiry;
import com.baosight.risk.service.riaa.entity.RiaaQuesType;
import com.baosight.risk.service.riaa.entity.RiaaQuesUser;
import com.baosight.risk.service.riaa.entity.RiquInquiryComp;
import com.baosight.risk.service.riaa.entity.RiquInquiryDetail;
import com.baosight.risk.service.riaa.vo.RiaaQuesCompVO;
import com.baosight.risk.service.riaa.vo.RiaaQuesInquiryVO;
import com.baosight.risk.service.riaa.vo.RiquInquiryCompVO;
import com.baosight.risk.service.system.entity.SysOperLog;
import com.baosight.risk.service.system.entity.SysRole;
import com.baosight.risk.service.system.entity.XsUser;
import com.baosight.risk.service.xtzy.entity.XtzyCompRole;
import com.baosight.risk.service.xtzy.entity.XtzyCompUser;
import com.baosight.risk.service.xtzy.entity.XtzyCompany;
import com.baosight.risk.service.xtzy.entity.XtzyRoleUser;
import com.baosight.risk.service.xtzy.entity.XtzyUser;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;


/**
 * 类 名: RiaaQuesImquiryServiceImpl
 * 作 者: gaohan
 * 创 建：2019年06月05日
 * 版 本：v2.2.0
 * 历 史: (版本) 作者 时间 注释
 */
@Service
public class RiaaQuesImquiryServiceImpl extends BaseServiceImpl<RiaaQuesInquiry> implements RiaaQuesInquiryService {

    @Autowired
    private RiaaQuesInquiryMapper riaaQuesInquiryMapper;

    @Autowired
    private RiquInquiryCompMapper riquInquiryCompMapper;

    @Autowired
    private RiaaQuesTypeMapper riaaQuesTypeMapper;

    @Autowired
    private RiaaQuesCompMapper riaaQuesCompMapper;

    @Autowired
    private RiaaQuesUserMapper riaaQuesUserMapper;

    @Autowired
    private RiquInquiryDetailMapper riquInquiryDetailMapper;

    @Autowired
    private FltdProcessService fltdProcessService;

    @Autowired
    private IXtzyCompanyService xtzyCompanyService;

    @Autowired
    private RiquInquiryCompService riquInquiryCompService;

    @Autowired
    private FlaaNodeAuthoService flaaNodeAuthoService;

    @Autowired
    private XtzyRoleUserMapper roleUserMapper;

    @Autowired
    private IXtzyUserService userService;

    @Autowired
    private IXtzyCompanyService companyService;

    @Autowired
    private XtzyCompUserMapper compUserMapper;

    @Autowired
    private XtzyCompRoleMapper compRoleMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private XsUserMapper xsUserMapper;

    @Override
    public BaseMapper getMapper() {
        return riaaQuesInquiryMapper;
    }

    @Override
    public List<RiaaQuesInquiry> selectList(RiaaQuesInquiry inquiry) {
        if (StringUtils.isNotEmpty(inquiry.getAcctYear())) {
            inquiry.setAcctYear(inquiry.getAcctYear().substring(0, 4));
        }
        List<RiaaQuesInquiry> inquiries = riaaQuesInquiryMapper.selectList(inquiry);
        //拼接下发单位
        String compNames = "";
        if (!CollectionUtils.isEmpty(inquiries)) {
            for (RiaaQuesInquiry quesInquiry : inquiries) {
                compNames = addCompName(riaaQuesCompMapper.getCompByQuId(quesInquiry.getId()));
                if (StringUtils.isNotEmpty(compNames)) {
                    quesInquiry.setExt1(compNames);
                }
            }
        }
        return inquiries;
    }

    public String addCompName(List<RiaaQuesCompVO> compList) {
        String compNames = "";
        if (!CollectionUtils.isEmpty(compList)) {
            for (RiaaQuesCompVO compVO : compList) {
                compNames = compNames + compVO.getSubmitCompName() + "，";

            }
            compNames = compNames.substring(0, compNames.length() - 1);
        }
        return compNames;
    }

    public String addUserName(String quId, String compId) {
        List<RiaaQuesUser> userList = riaaQuesUserMapper.getUserByCompId(quId, compId);
        if (CollectionUtils.isEmpty(userList)) {
            return null;
        }
        List<String> nameList = userList.stream().map(RiaaQuesUser::getSubmitUserName).collect(Collectors.toList());
        return nameList.toString();
    }

    @Override
    public RiaaQuesInquiryVO selectById(String quId) {
        RiaaQuesInquiryVO inquiryVO = new RiaaQuesInquiryVO();
        RiaaQuesInquiry inquiry = riaaQuesInquiryMapper.selectByPrimaryKey(quId);
        BeanUtils.copyBeanProp(inquiryVO, inquiry);
        List<RiaaQuesCompVO> compList = riaaQuesCompMapper.getCompByQuId(quId);
        inquiryVO.setCompList(compList);
        inquiryVO.setTypeList(riaaQuesTypeMapper.getTypeByQuId(quId));
        return inquiryVO;
    }

    @Override
    public RiaaQuesInquiryVO saveInquiry(RiaaQuesInquiryVO inquiryVO) {
        RiaaQuesInquiryVO quesInquiry = new RiaaQuesInquiryVO();
        if (StringUtils.isNotEmpty(inquiryVO.getId())) {
            quesInquiry = (RiaaQuesInquiryVO) BeanUtils.updateBean(inquiryVO);
            riaaQuesInquiryMapper.updateByPrimaryKeySelective(quesInquiry);
            //先删除后新增
            riaaQuesCompMapper.deletBuQuId(inquiryVO.getId());
            riaaQuesUserMapper.deletBuQuId(inquiryVO.getId());
            riaaQuesTypeMapper.deleteByQuId(inquiryVO.getId());
        } else {
            quesInquiry = (RiaaQuesInquiryVO) BeanUtils.initBean(inquiryVO);
            riaaQuesInquiryMapper.insert(quesInquiry);
        }
        insertComp(inquiryVO);
        saveType(inquiryVO);

        return quesInquiry;
    }

    /**
     * 新增下发组织信息
     */
    public void insertComp(RiaaQuesInquiryVO inquiryVO) {
        for (RiaaQuesCompVO quesComp : inquiryVO.getCompList()) {
            quesComp = (RiaaQuesCompVO) BeanUtils.initBean(quesComp);
            quesComp.setQuId(inquiryVO.getId());
            riaaQuesCompMapper.insert(quesComp);
        }
    }


    public void saveType(RiaaQuesInquiryVO inquiryVO) {
        if (CollectionUtils.isNotEmpty(inquiryVO.getTypeList())) {
            for (RiaaQuesType type : inquiryVO.getTypeList()) {
                type = (RiaaQuesType) BeanUtils.initBean(type);
                type.setQuId(inquiryVO.getId());
                int rowOrder;
                Integer i = riaaQuesTypeMapper.queryMaxRowOrde(inquiryVO.getId());
                if (i == null) {
                    rowOrder = 1;
                } else {
                    rowOrder = i + 1;
                }
                type.setRowOrder(rowOrder);
                riaaQuesTypeMapper.insert(type);
            }
        }
    }


    @Override
    public void saveSendInquiry(String id,String flag) throws Exception {
        if("A".equals(flag)){
            saveInquiryCompA(id);
        } else {
            saveInquiryCompB(id);
        }
    }

    private void saveInquiryCompA(String id) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            RiaaQuesInquiryVO inquiryVO = selectById(id);
            List<RiaaQuesCompVO> compList = inquiryVO.getCompList();
            if(CollectionUtils.isEmpty(compList)){
                throw new Exception("问卷未选择下发单位,请填写!");
            }
            if (CollectionUtils.isEmpty(inquiryVO.getTypeList())) {
                throw new Exception("问卷选项未填写,请填写!");
            }
            FltdTaskVO taskVO = new FltdTaskVO();
            taskVO.setFlowNo("wenjuanzhizuo");
            taskVO.setFlowName("问卷制作");
            taskVO.setAcctYear(inquiryVO.getAcctYear());
            for (RiaaQuesCompVO compVO : compList) {
                List<RiaaQuesCompVO> vos = compList.stream().filter
                        (o -> compVO.getSubmitCompCode().equals(o.getSubmitCompCode())).collect(Collectors.toList());
                if (vos.size() > 1) {
                    throw new Exception(compVO.getSubmitCompName() + "存在多条数据,请修改!");
                }
                if (StringUtils.isEmpty(compVO.getSubmitUserCode())) {
                    throw new Exception(compVO.getSubmitCompName() + "未配置流程对应的角色!");
                }
                List<RiquInquiryComp> list = getInquiryCompA(compVO);
                if (CollectionUtils.isNotEmpty(list)) {
                    continue;
                }
                RiquInquiryComp comp = addInquiryCompA(inquiryVO, compVO);
                List<XtzyUser> userList = new ArrayList<>();
                XtzyUser user = new XtzyUser();
                user.setUserCode(compVO.getSubmitUserCode());
                user.setUserDesc(compVO.getSubmitUserName());
                user.setExt1(compVO.getSubmitCompCode());
                user.setExt2(compVO.getSubmitCompName());
                userList.add(user);
                taskVO.setCustomUsers(userList);
                XtzyCompany xtzyCompany = new XtzyCompany();
                xtzyCompany.setCompCode(comp.getSubmitCompCode());
                xtzyCompany.setCompName(comp.getSubmitCompName());
                taskVO.setCustomCompany(xtzyCompany);
                taskVO.setDeptCode(comp.getSubmitCompCode());
                taskVO.setDeptName(comp.getSubmitCompName());
                taskVO.setCompCode(comp.getSubmitCompCode());
                taskVO.setCompName(comp.getSubmitCompName());
                taskVO.setCompName(comp.getSubmitCompName());
                String bizName = inquiryVO.getSendCompName() + "下发" + taskVO.getAcctYear() + inquiryVO.getQuName() + "-" + taskVO.getCustomCompany().getCompName();
                String bizDesc = taskVO.getAcctYear() + "年度-" + taskVO.getCustomCompany().getCompName() + "-问卷分配";
                taskVO.setBizName(bizName);
                taskVO.setBizDesc(bizDesc);
                taskVO.setBizGuid(comp.getId());
                taskVO.setGroupCondition(taskVO.getAcctYear());
                taskVO.setManageCompCode(inquiryVO.getSendCompCode());
                taskVO.setManageCompName(inquiryVO.getSendCompName());
                try {
                    //启动流程
                    fltdProcessService.doStart(taskVO);
                    logs.add(fltdProcessService.getLog("问卷分配-流程启动成功", 0, "业务id：" + comp.getId(), null));
                } catch (Exception e) {
                    logs.add(fltdProcessService.getLog("问卷分配-流程启动失败", 1, e.getMessage(), null));
                    error = e;
                    break;
                }
            }
            inquiryVO.setStatus("10");
            inquiryVO.setStatusName("已下发");
            riaaQuesInquiryMapper.updateByPrimaryKeySelective(inquiryVO);
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("问卷分配-下发异常", 1, e.getMessage(), null));
            error = e;
        }
        //保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }

    private void saveInquiryCompB(String id) throws Exception {
        List<SysOperLog> logs = new ArrayList<>();
        Exception error = null;
        try {
            RiquInquiryComp comp = riquInquiryCompMapper.selectByPrimaryKey(id);
            List<RiquInquiryComp> compList = riquInquiryCompMapper.queryByParentGuid(id,"A01");
            if (CollectionUtils.isEmpty(compList)) {
                throw new Exception(comp.getSubmitCompName() + "公司下没有需要分配的数据!");
            }
            List<RiaaQuesType> quesTypeList = riaaQuesTypeMapper.getTypeByQuId(comp.getQuId());
            FltdTaskVO taskVO = new FltdTaskVO();
            taskVO.setFlowNo("wenjuantianbao");
            taskVO.setFlowName("问卷填报");
            taskVO.setAcctYear(comp.getAcctYear());
            for (RiquInquiryComp inquiryComp : compList) {
                addInquiryCompB(inquiryComp, quesTypeList);
                List<XtzyUser> list = Lists.newArrayList();
                XtzyUser u = new XtzyUser();
                u.setUserCode(inquiryComp.getSubmitUserCode());
                u.setUserDesc(inquiryComp.getSubmitUserName());
                u.setExt1(inquiryComp.getSubmitCompCode());
                u.setExt2(inquiryComp.getSubmitCompName());
                list.add(u);
                taskVO.setCustomUsers(list);
                XtzyCompany xtzyCompany = new XtzyCompany();
                xtzyCompany.setCompCode(inquiryComp.getSubmitCompCode());
                xtzyCompany.setCompName(inquiryComp.getSubmitCompName());
                taskVO.setCustomCompany(xtzyCompany);
                taskVO.setDeptCode(inquiryComp.getSubmitCompCode());
                taskVO.setDeptName(inquiryComp.getSubmitCompName());
                taskVO.setCompCode(inquiryComp.getSubmitCompCode());
                taskVO.setCompName(inquiryComp.getSubmitCompName());
                taskVO.setCompName(inquiryComp.getSubmitCompName());
                String bizName = inquiryComp.getSendCompName() + "下发" + taskVO.getAcctYear() + inquiryComp.getQuName() + "-" + taskVO.getCustomCompany().getCompName();
                String bizDesc = taskVO.getAcctYear() + "年度-" + taskVO.getCustomCompany().getCompName() + taskVO.getCustomUsers().get(0).getUserDesc() + "-问卷填报";
                taskVO.setBizName(bizName);
                taskVO.setBizDesc(bizDesc);
                taskVO.setBizGuid(inquiryComp.getId());
                taskVO.setGroupCondition(taskVO.getAcctYear());
                try {
                    //启动流程
                    fltdProcessService.doStart(taskVO);
                    logs.add(fltdProcessService.getLog("问卷填报-流程启动成功", 0, "业务id：" + comp.getId(), null));
                } catch (Exception e) {
                    logs.add(fltdProcessService.getLog("问卷填报-流程启动失败", 1, e.getMessage(), null));
                    error = e;
                    break;
                }
            }
            comp.setStatus("A02");
            comp.setStatusName("待填报");
            riquInquiryCompMapper.updateByPrimaryKeySelective(comp);
        } catch (Exception e) {
            logs.add(fltdProcessService.getLog("问卷填报-下发异常", 1, e.getMessage(), null));
            error = e;
        }
        //保存日志到数据库
        AsyncManager.me().execute(AsyncFactory.batchRecordOper(logs));
        if (error != null) {
            throw error;
        }

    }
    /**
     * 流程待分配将下发单位数据插入问卷调研结果表
     * @param inquiryVO
     * @param compVO
     */
    private  RiquInquiryComp addInquiryCompA(RiaaQuesInquiryVO inquiryVO,RiaaQuesCompVO compVO){
        RiquInquiryComp inquiryComp = new RiquInquiryComp();
        inquiryComp.setQuId(inquiryVO.getId());
        inquiryComp.setQuName(inquiryVO.getQuName());
        inquiryComp.setQuDesc(inquiryVO.getQuDesc());
        inquiryComp.setAcctYear(inquiryVO.getAcctYear());
        inquiryComp.setSendCompCode(inquiryVO.getSendCompCode());
        inquiryComp.setSendCompName(inquiryVO.getSendCompName());
        inquiryComp.setSubmitCompCode(compVO.getSubmitCompCode());
        inquiryComp.setSubmitCompName(compVO.getSubmitCompName());
//        inquiryComp.setRowOrder(compVO.getRowOrder());
        inquiryComp.setStatus("A01");
        inquiryComp.setStatusName("待分配");
        inquiryComp.setBizType("A");
        inquiryComp.setBizTypeName("问卷分配");
        inquiryComp.setParentGuid("0");
        inquiryComp = (RiquInquiryComp) BeanUtils.initBean(inquiryComp);
        riquInquiryCompMapper.insert(inquiryComp);
        return inquiryComp;
    }

    /**
     * 流程待填报下发将填报人员插入问卷调研结果和明细表
     * @param inquiryComp
     * @return
     */
    private void addInquiryCompB(RiquInquiryComp inquiryComp,List<RiaaQuesType> quesTypeList){
        inquiryComp.setStatus("A02");
        inquiryComp.setStatusName("待填报");
        riquInquiryCompMapper.updateByPrimaryKeySelective(inquiryComp);
        for (RiaaQuesType quesType : quesTypeList) {
            RiquInquiryDetail inquiryDetail = new RiquInquiryDetail();
            BeanUtils.copyBeanProp(inquiryDetail, quesType);
            inquiryDetail.setQuResultId(inquiryComp.getId());
            inquiryDetail.setSubmitCompCode(inquiryComp.getSubmitCompCode());
            inquiryDetail.setSubmitCompName(inquiryComp.getSubmitCompName());
            inquiryDetail = (RiquInquiryDetail) BeanUtils.initBean(inquiryDetail);
            //0代表未选择，1代表已经选择
            inquiryDetail.setAnswerDesc("0");
            inquiryDetail.setRowOrder(quesType.getRowOrder());
            inquiryDetail.setCreateFlag("0");//制作下发标识
            inquiryDetail.setCreateBy(quesType.getCreateBy());
            riquInquiryDetailMapper.insert(inquiryDetail);
        }
    }

    /**
     * 问卷下发，判断下发单位是否有下发过的数据
     * @param quesComp
     * @return
     */
    private List<RiquInquiryComp> getInquiryCompA(RiaaQuesCompVO quesComp){
        Map<String,Object> map = Maps.newHashMap();
        map.put("quId", quesComp.getQuId());
        map.put("submitCompCode", quesComp.getSubmitCompCode());
        map.put("bizType", "A");
        return queryExist(map);
    }

    /**
     * 问卷下发，判断指定到填报人员时候下发过数据
     * @return
     */
    private List<RiquInquiryComp> getInquiryCompB(RiaaQuesUser quesUser){
        Map<String,Object> map = Maps.newHashMap();
        map.put("quId", quesUser.getQuId());
        map.put("submitCompCode", quesUser.getSubmitCompCode());
        map.put("submitUserCode", quesUser.getSubmitUserCode());
        map.put("bizType", "B");
        return queryExist(map);
    }

    private List<RiquInquiryComp> queryExist( Map<String, Object> map) {
        return riquInquiryCompMapper.queryExist(map);
    }



    @Override
    public Integer deleteInquiry(String id) {
        riaaQuesCompMapper.deletBuQuId(id);
        riaaQuesUserMapper.deletBuQuId(id);
        riaaQuesTypeMapper.deleteByQuId(id);
        return riaaQuesInquiryMapper.deleteByPrimaryKey(id);
    }

    @Override
    public Map exportQuesBGTA(String id) {
        Map map = new HashMap();
        String BGTA = "BGTA";
        String BASE = "BASE";

        RiquInquiryCompVO inquiryCompVO = riquInquiryCompService.getById(id);
        String quDesc = inquiryCompVO.getQuDesc();
        String greetings = "领导，您好：";
        if (StringUtils.isNotEmpty(quDesc)) {
            String[] split = quDesc.split("：\n");
            if (split.length > 1) {
                greetings = split[0] + "：";
                quDesc = quDesc.substring(greetings.length()+1, quDesc.length());
            }
        }
        // 问卷标题
        map.put("quName", inquiryCompVO.getQuName());
        // 问候语
        map.put("greetings", greetings);
        // 填报说明
        map.put("quDesc", quDesc);
        // 总部数据
        List<RiquInquiryDetail> BGTADetail = inquiryCompVO.getRiquInquiryBGTADetail();
        // 各基地数据
        List<RiquInquiryDetail> BASEDetail = inquiryCompVO.getRiquInquiryDetail();

        // 增加其他事项
        BGTADetail = addOther(BGTADetail, BGTA);
        BASEDetail = addOther(BASEDetail, BASE);

        // 转换成自定义列表
        List<Map<String, Object>> BGTADetailList = parseQues(BGTADetail);
        List<Map<String, Object>> BASEDetailList = parseQues(BASEDetail);

        int BGTASize = BGTADetail==null ? 0 : BGTADetail.size();
        int BSAESize = BASEDetail==null ? 0 : BASEDetail.size();
        int rowCount = BGTASize > BSAESize? BGTASize : BSAESize;
        int colCount = 5;

        List<List<Map<String, Object>>> rows = new ArrayList<>();

        // 添加默认行，填充所有单元格
        for (int i = 0; i < rowCount; i++) {
            List<Map<String, Object>> row = new ArrayList<>();
            for (int j = 0; j < colCount; j++) {
                Map<String, Object> cell = new HashMap<>();
                cell.put("type", "text");
                cell.put("content", "");
                cell.put("merge", "");
                cell.put("selected", "");
                row.add(cell);
            }
            rows.add(row);
        }

        // 转换成表格结构
        addRow(rows, BGTADetailList, BGTA);
        addRow(rows, BASEDetailList, BASE);

        map.put("rows", rows);
        return map;
    }
    
    @Override
    public Map exportQues(String id) {
        Map map = new HashMap();
        String BGTA = "BGTA";

        RiquInquiryCompVO inquiryCompVO = riquInquiryCompService.getById(id);
        String quDesc = inquiryCompVO.getQuDesc();
        String greetings = "领导，您好：";
        if (StringUtils.isNotEmpty(quDesc)) {
            String[] split = quDesc.split("：\n");
            if (split.length > 1) {
                greetings = split[0] + "：";
                quDesc = quDesc.substring(greetings.length()+1, quDesc.length());
            }
        }
        // 问卷标题
        map.put("quName", inquiryCompVO.getQuName());
        // 问候语
        map.put("greetings", greetings);
        // 填报说明
        map.put("quDesc", quDesc);
        // 总部数据
        List<RiquInquiryDetail> BGTADetail = inquiryCompVO.getRiquInquiryBGTADetail();


        // 增加其他事项
        BGTADetail = addOther(BGTADetail, BGTA);


        // 转换成自定义列表
        List<Map<String, Object>> BGTADetailList = parseQues(BGTADetail);

        int colCount = 3;

        List<List<Map<String, Object>>> rows = new ArrayList<>();

        // 添加默认行，填充所有单元格
        for (int i = 0; i < BGTADetail.size(); i++) {
	        List<Map<String, Object>> row = new ArrayList<Map<String, Object>>();
	        for (int j = 0; j < colCount; j++) {
	            Map<String, Object> cell = new HashMap<String, Object>();
	            cell.put("type", "text");
	            cell.put("content", "");
	            cell.put("merge", "");
	            cell.put("selected", "");
	            row.add(cell);
	        }
	        rows.add(row);
        }
        // 转换成表格结构
        addRow(rows, BGTADetailList, BGTA);
        
        for(int i=0;i<rows.size();i++){
        	List<Map<String, Object>> ro = rows.get(i);
        	Map<String, Object> cell = ro.get(0);
        	cell.put("content", i+1+"");
        }

        map.put("rows", rows);
        return map;
    }

    @Override
    public List<Map> queryCompUser(Map<String, Object> map) throws Exception {
//        List<Map> resultMap = Lists.newArrayList();
        // 根据流程编码和流程节点查询出流程节点的授权信息
        FlaaNodeAuthoVO nodeAuthoVO =
                flaaNodeAuthoService.selectNodeInfo(map.get("flowNo").toString(),map.get("nodeCode").toString());
        Map<String, Object> param = Maps.newHashMap();
        param.put("roleKey", nodeAuthoVO.getRoleCode());
        param.put("compCode", map.get("compCode"));
        List<Map> list = roleUserMapper.queryByUser(param);
        return list;
    }

    /**
     * 问卷制作选项的删除
     * @param ids
     * @return
     */
    @Override
    public void deleteType(List<String> ids) {
        ids.forEach(id -> {
            riaaQuesTypeMapper.deleteByPrimaryKey(id);
        });
    }

    /**
     * 增加其他事项
     *
     */
    private List<RiquInquiryDetail> addOther(List<RiquInquiryDetail> detailList, String type) {
        List<RiquInquiryDetail> otherList = new ArrayList<>();
        List<RiquInquiryDetail> orgList = new ArrayList<>();
        String qt = "QT";
        String qtName = "其他事项";

        for (RiquInquiryDetail inquiryDetail : detailList) {
            if (qt.equals(inquiryDetail.getFieldCode())) {
                otherList.add(inquiryDetail);
            } else {
                orgList.add(inquiryDetail);
            }
        }

        if (CollectionUtils.isNotEmpty(otherList)) {
            orgList.addAll(otherList);
        } else {
            RiquInquiryDetail otherDetail = new RiquInquiryDetail();
            if ("BGTA".equals(type)) {
                otherDetail.setDutyCompCode("BGTA");
                otherDetail.setDutyCompName("总部");
            } else {
                otherDetail.setDutyCompCode("BASE");
                otherDetail.setDutyCompName(qtName);
            }
            otherDetail.setFieldCode(qt);
            otherDetail.setFieldName(qtName);
            otherDetail.setQuesName("");
            otherDetail.setAnswerDesc("0");
            orgList.add(otherDetail);
        }
        return orgList;
    }

    /**
     * 转换问卷列表，按单位和风险类别分组
     *
     */
    private List<Map<String, Object>> parseQues(List<RiquInquiryDetail> detailList) {
        Map<String, Map<String, Object>> detailMap = new LinkedHashMap<>();
        if (CollectionUtils.isNotEmpty(detailList)) {
            for (RiquInquiryDetail inquiryDetail : detailList) {
                String key = inquiryDetail.getDutyCompCode() + inquiryDetail.getFieldCode();
                if (detailMap.containsKey(key)) {
                    Map<String, Object> detail = detailMap.get(key);
                    List<RiquInquiryDetail> ques = (List<RiquInquiryDetail>) detail.get("ques");
                    ques.add(inquiryDetail);
                } else {
                    List<RiquInquiryDetail> ques = new ArrayList<>();
                    ques.add(inquiryDetail);
                    Map<String, Object> detail = new HashMap<>();
                    detail.put("dutyCompCode", inquiryDetail.getDutyCompCode());
                    detail.put("dutyCompName", inquiryDetail.getDutyCompName());
                    detail.put("fieldCode", inquiryDetail.getFieldCode());
                    detail.put("fieldName", inquiryDetail.getFieldName());
                    detail.put("ques", ques);
                    detailMap.put(key, detail);
                }
            }
        }

        List<Map<String, Object>> details = new ArrayList<>();
        for (String key : detailMap.keySet()) {
            details.add(detailMap.get(key));
        }
        return details;
    }

    /**
     * 转换行数据，把问卷列表转换成自定义的表格结构
     *
     */
    private void addRow(List<List<Map<String, Object>>> rows, List<Map<String, Object>> DetailList, String type) {
        int rowIndex = 0;
        for (Map<String, Object> detailMap : DetailList) {
            Object dutyCompName = detailMap.get("dutyCompName");
            Object fieldName = detailMap.get("fieldName");
            List<RiquInquiryDetail> ques = (List<RiquInquiryDetail>) detailMap.get("ques");

            if (CollectionUtils.isNotEmpty(ques)) {
                for (int i = 0; i < ques.size(); i++) {
                    RiquInquiryDetail que = ques.get(i);
                    List<Map<String, Object>> row = rows.get(rowIndex);
                    int col = "BGTA".equals(type) ? 0: 3;
                    String merge = ques.size() == 1 ? "" : i==0? "restart": "continue";
                    Map<String, Object> compCell = row.get(col);
                    compCell.put("type", "text");
                    compCell.put("content", dutyCompName);
                    compCell.put("merge", merge);
                    col++;

                    if ("BGTA".equals(type)) {
                        Map<String, Object> fieldCell = row.get(col);
                        fieldCell.put("type", "text");
                        fieldCell.put("content", fieldName);
                        fieldCell.put("merge", merge);
                        col++;
                    }

                    Map<String, Object> quesCell = row.get(col);
                    quesCell.put("type", "check");
                    quesCell.put("content", que.getQuesName());
                    quesCell.put("selected", que.getAnswerDesc());

                    rowIndex++;
                }
            }
        }
    }


    @Override
    public void updateSubmitUser(SyncEmpleeEntitiy employee, RiquInquiryComp riquInquiryComp) throws Exception {
        // 添加人员到系统
        Map<String, Object> resultMap = addUserToSystem(employee, riquInquiryComp.getSubmitCompCode(), "COMP06");
        XtzyUser user = (XtzyUser) resultMap.get("user");

        // 修改问卷所属单位的管理员
        RiquInquiryComp ric = new RiquInquiryComp();
        ric.setId(riquInquiryComp.getId());
        ric.setSubmitUserCode(user.getUserCode());
        ric.setSubmitUserName(user.getUserDesc());
        if(riquInquiryCompMapper.updateSubmitUser(ric) < 1) {
            throw new Exception("操作失败");
        }

        // 删除原来的管理员授权
        if (StringUtils.isNotEmpty(riquInquiryComp.getSubmitUserCode())) {
            if(roleUserMapper.deleteByCompIdAndUserCode(riquInquiryComp.getSubmitCompCode(), riquInquiryComp.getSubmitUserCode()) < 1) {
                throw new Exception("操作失败");
            }
        }

    }



    @Override
    public void handOverUser(XtzyUser xtzyUser, RiquInquiryComp riquInquiryComp) throws Exception {
        // 修改问卷所属单位的管理员
        RiquInquiryComp ric = new RiquInquiryComp();
        ric.setId(riquInquiryComp.getId());
        ric.setSubmitUserCode(xtzyUser.getUserCode());
        ric.setSubmitUserName(xtzyUser.getUserDesc());
        if(riquInquiryCompMapper.updateSubmitUser(ric) < 1) {
            throw new Exception("操作失败");
        }

//        // 删除原来的管理员授权
//        if (StringUtils.isNotEmpty(riquInquiryComp.getSubmitUserCode())) {
//            roleUserMapper.deleteByCompIdAndUserCode(riquInquiryComp.getSubmitCompCode(), riquInquiryComp.getSubmitUserCode());
//        }

    }


    /**
     * （通用）从EHR添加人员到系统，并赋予角色
     *
     */
    @Override
    public Map<String, Object> addUserToSystem(SyncEmpleeEntitiy employee, String deptCode, String roleCode) throws Exception {
        Map<String, Object> resultMap = new HashMap<>();

        // 查询单位
        XtzyCompany xtzyCompany = companyService.get(deptCode);
        // 添加到系统用户表
        XtzyUser user = null;
        XtzyUser existUser = userService.selectByName(employee.getEmpCode());
        if (existUser != null) {
            user = existUser;
        } else {
            // 只有不存在系统的时候才添加
            user = (XtzyUser) BeanUtils.initBean(new XtzyUser());
            user.setId(IDGenerator.getIdStr());
            user.setUserCode(employee.getEmpCode());
            user.setUserDesc(employee.getEmpName());
            user.setPhoneCode(employee.getMobile());
            user.setEmail(employee.getEmail());
            user.setDuty(employee.getPostName());
            user.setStatus("10");
            user.setOrgCode(xtzyCompany.getCompCode());
            user.setOrgName(xtzyCompany.getCompNameL());
            if(userService.insertUser(user) < 1) {
                throw new Exception("操作失败");
            }

            // 添加到平台用户表
            XsUser xsUserParam = new XsUser();
            xsUserParam.setLoginName(user.getUserCode());
            if(xsUserMapper.selectOne(xsUserParam) == null) {
                userService.addUserToIplat(user);
            }
        }

        if (user == null) {
            throw new Exception("操作失败");
        }

        resultMap.put("user", user);
        resultMap.put("company", xtzyCompany);

        // 添加到单位
        // 查询单位是否已经存在该用户，没有则添加
        if(compUserMapper.getUserByCompIdAndUser(xtzyCompany.getCompCode(), user.getUserCode()) == null) {
            XtzyCompUser xtzyCompUser = (XtzyCompUser) BeanUtils.initBean(new XtzyCompUser());
            xtzyCompUser.setUserId(user.getId());
            xtzyCompUser.setUserCode(user.getUserCode());
            xtzyCompUser.setUserDesc(user.getUserDesc());
            xtzyCompUser.setCompId(xtzyCompany.getId());
            xtzyCompUser.setCompCode(xtzyCompany.getCompCode());
            xtzyCompUser.setCompName(xtzyCompany.getCompName());
            xtzyCompUser.setPathCode(xtzyCompany.getPathCode());
            xtzyCompUser.setPathName(xtzyCompany.getPathName());
            if(compUserMapper.insert(xtzyCompUser) < 1) {
                throw new Exception("操作失败");
            }
        }

        // 添加角色
        SysRole sysRole = new SysRole();
        sysRole.setRoleKey(roleCode);
        SysRole role = sysRoleMapper.selectOne(sysRole);

        XtzyCompRole param = new XtzyCompRole();
        param.setRoleCode(role.getRoleKey());
        param.setCompCode(xtzyCompany.getCompCode());
        // 查询单位是否已经存在该角色，没有则添加
        if (compRoleMapper.selectOne(param) == null) {
            XtzyCompRole xtzyCompRole = (XtzyCompRole) BeanUtils.initBean(new XtzyCompRole());
            xtzyCompRole.setRoleId(role.getId());
            xtzyCompRole.setRoleCode(role.getRoleKey());
            xtzyCompRole.setRoleDesc(role.getRoleName());
            xtzyCompRole.setCompId(xtzyCompany.getId());
            xtzyCompRole.setCompCode(xtzyCompany.getCompCode());
            xtzyCompRole.setCompName(xtzyCompany.getCompName());
            xtzyCompRole.setPathCode(xtzyCompany.getPathCode());
            xtzyCompRole.setPathName(xtzyCompany.getPathName());
            if(compRoleMapper.insert(xtzyCompRole) < 1) {
                throw new Exception("操作失败");
            }
        }

        // 添加到人员角色表
        XtzyRoleUser roleUserParam = new XtzyRoleUser();
        roleUserParam.setUserCode(user.getUserCode());
        roleUserParam.setRoleCode(role.getId());
        roleUserParam.setCompCode(xtzyCompany.getCompCode());
        if (roleUserMapper.selectOne(roleUserParam) == null) {
            XtzyRoleUser xtzyRoleUser = (XtzyRoleUser) BeanUtils.initBean(new XtzyRoleUser());
            xtzyRoleUser.setRoleCode(role.getId());
            xtzyRoleUser.setRoleName(role.getRoleName());
            xtzyRoleUser.setUserGuid(user.getId());
            xtzyRoleUser.setUserCode(user.getUserCode());
            xtzyRoleUser.setUserDesc(user.getUserDesc());
            xtzyRoleUser.setCompCode(xtzyCompany.getCompCode());
            xtzyRoleUser.setCompName(xtzyCompany.getCompName());
            xtzyRoleUser.setPathCode(xtzyCompany.getPathCode());
            xtzyRoleUser.setPathName(xtzyCompany.getPathName());
            xtzyRoleUser.setRoleCompCode(xtzyCompany.getCompCode());
            xtzyRoleUser.setRoleCompName(xtzyCompany.getCompName());
            if(roleUserMapper.insert(xtzyRoleUser) < 1) {
                throw new Exception("操作失败");
            }
        }
        return resultMap;
    }

}
